package controllers

import (
	"github.com/kataras/iris"
	"github.com/kataras/iris/mvc"
	"tizhi_front/model"
	"tizhi_front/nspel"
	"tizhi_front/request"
	"tizhi_front/response"
	"tizhi_front/utils"
)

type EvaluationController struct {
	Ctx iris.Context
}

func (c *EvaluationController) BeforeActivation(b mvc.BeforeActivation) {
	b.Handle("PUT", "/", "AddEvaluation", beforeAddEvaluation)
	b.Handle("POST", "/list", "GetEvaluation", beforeCommonToken)
	b.Handle("POST", "/{id:long}", "UpdateEvaluation", beforeAddEvaluation)
	b.Handle("DELETE", "/{id:long}", "DeleteEvaluation", beforeCommonToken)
}

func beforeAddEvaluation(ctx iris.Context) {
	req := request.AddEvaluation{}
	err := ctx.ReadJSON(&req)
	if err != nil {
		_, _ = ctx.JSON(response.InvalidParameters)
		return
	}
	if !utils.ValidateToken(&req.TokenInfo) {
		ctx.StatusCode(403)
		_, _ = ctx.JSON(response.InvalidParameters)
		return
	}
	ctx.Values().Set("uid", req.TokenInfo.Uid)
	ctx.Values().Set("data", req.EvaluationInfo)
	ctx.Next()
}

// @Title Self Evaluation Add
// @Description 创建自我评测
// @Tags evaluation
// @Param	body body request.AddEvaluation true " "
// @Success 0	{object} response.JsonResponse
// @Failure 1 {string} string "用户未登录或者登陆已过期"
// @Failure 2 {string} string "系统错误，获取失败，具体error信息为系统报错信息"
// @router /evaluation [put]
func (c *EvaluationController) AddEvaluation() response.JsonResponse {
	uid, err := c.Ctx.Values().GetInt64("uid")
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	data := c.Ctx.Values().Get("data").(request.EvaluationInfo)
	selfEvaluation, err := data.Calculate(uid)
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	err = selfEvaluation.Insert()
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	utils.NewMessage(uid, "创建自我评测成功")
	return response.JsonResponse{
		ErrCode: 0,
		ErrInfo: "",
		Data:    "",
	}
}

// @Title Self Evaluation Get
// @Description 获取自我评测
// @Tags evaluation
// @Param	body body response.TokenInfo true " "
// @Success 0	{object} response.EvaluationDetail
// @Failure 1 {string} string "用户未登录或者登陆已过期"
// @Failure 2 {string} string "系统错误，获取失败，具体error信息为系统报错信息"
// @router /evaluation/list [post]
func (c *EvaluationController) GetEvaluation() response.JsonResponse {
	uid, err := c.Ctx.Values().GetInt64("uid")
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	selfEvaluation := model.SelfEvaluationE{}
	selfEvaluations, err := selfEvaluation.SelectAllByStudentIdOrderByCreatedAt(uid)
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	res := response.EvaluationInfo{
		Shape:      []response.EvaluationChartInfo{},
		Function:   []response.EvaluationChartInfo{},
		Quality:    []response.EvaluationChartInfo{},
		Evaluation: []response.EvaluationDetail{},
	}
	res.Shape = make([]response.EvaluationChartInfo, len(selfEvaluations))
	res.Function = make([]response.EvaluationChartInfo, len(selfEvaluations))
	res.Quality = make([]response.EvaluationChartInfo, len(selfEvaluations))
	res.Evaluation = make([]response.EvaluationDetail, len(selfEvaluations))
	for i := 0; i < len(selfEvaluations); i++ {
		res.Shape[i] = response.EvaluationChartInfo{
			Score: selfEvaluations[i].BodyMassIndexScore,
			Date:  selfEvaluations[i].CreatedAt.Format("2006-01-02 15:04:05"),
		}
		res.Function[i] = response.EvaluationChartInfo{
			Score: selfEvaluations[i].VitalCapacityScore,
			Date:  res.Shape[i].Date,
		}
		res.Quality[i] = response.EvaluationChartInfo{
			Score: (selfEvaluations[i].FiftyMetersScore + selfEvaluations[i].SitAndReachScore + selfEvaluations[i].OneMinuteRopeSkippingScore + selfEvaluations[i].OneMinuteSipUpScore) / 4,
			Date:  res.Shape[i].Date,
		}
		res.Evaluation[i] = response.EvaluationDetail{
			Id:                    selfEvaluations[i].Id,
			Title:                 selfEvaluations[i].Title,
			Height:                selfEvaluations[i].Height,
			Weight:                selfEvaluations[i].Weight,
			VitalCapacity:         selfEvaluations[i].VitalCapacity,
			FiftyMeters:           selfEvaluations[i].FiftyMeters,
			SitAndReach:           selfEvaluations[i].SitAndReach,
			OneMinuteRopeSkipping: selfEvaluations[i].OneMinuteRopeSkipping,
			OneMinuteSitUp:        selfEvaluations[i].OneMinuteSitUp,
			Date:                  selfEvaluations[i].CreatedAt.Format("2006-01-02"),
		}
	}
	return response.JsonResponse{
		ErrCode: 0,
		ErrInfo: "",
		Data:    res,
	}
}

// @Title Self Evaluation Update
// @Description 更新自我评测
// @Tags evaluation
// @Param	id path int64	true "id for Evaluation"
// @Param	body body request.AddEvaluation true " "
// @Success 0	{object} response.JsonResponse
// @Failure 1 {string} string "用户未登录或者登陆已过期"
// @Failure 2 {string} string "系统错误，获取失败，具体error信息为系统报错信息"
// @router /evaluation/{id} [post]
func (c *EvaluationController) UpdateEvaluation(id int64) response.JsonResponse {
	uid, err := c.Ctx.Values().GetInt64("uid")
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	data := c.Ctx.Values().Get("data").(request.EvaluationInfo)
	selfEvaluation, err := data.Calculate(uid)
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	err = selfEvaluation.UpdateByIdStudentId(id)
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	utils.NewMessage(uid, "更新自我评测成功")
	return response.JsonResponse{
		ErrCode: 0,
		ErrInfo: "",
		Data:    "",
	}
}

// @Title Self Evaluation Delete
// @Description 删除自我评测
// @Tags evaluation
// @Param	id path int64	true "id for Evaluation"
// @Param	body body response.TokenInfo true " "
// @Success 0	{object} response.JsonResponse
// @Failure 1 {string} string "用户未登录或者登陆已过期"
// @Failure 2 {string} string "系统错误，获取失败，具体error信息为系统报错信息"
// @router /evaluation/{id} [delete]
func (c *EvaluationController) DeleteEvaluation(id int64) response.JsonResponse {
	uid, err := c.Ctx.Values().GetInt64("uid")
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	selfEvaluation := model.SelfEvaluationE{}
	err = selfEvaluation.DeleteByIdStudentId(id, uid)
	if err != nil {
		nspel.Error(err)
		return response.JsonResponse{
			ErrCode: 2,
			ErrInfo: err.Error(),
			Data:    "",
		}
	}
	utils.NewMessage(uid, "删除自我评测成功")
	return response.JsonResponse{
		ErrCode: 0,
		ErrInfo: "",
		Data:    "",
	}
}
